﻿CREATE FUNCTION NextPaymentDate(
	@DateStart datetime,
	@PaymentsPerYear tinyint,
	@Periods int
)RETURNS datetime WITH SCHEMABINDING AS BEGIN
DECLARE @Date datetime SET @Date =
		CASE @PaymentsPerYear
			 WHEN 12 THEN DATEADD(mm,@Periods,@DateStart)
			 WHEN 24 THEN DATEADD(mm,@Periods/2,@DateStart)
			 WHEN 26 THEN DATEADD(wk,2*@Periods,@DateStart)
			 WHEN 52 THEN DATEADD(wk,1*@Periods,@DateStart)
		END
IF @PaymentsPerYear = 24 AND @Periods % 2 =1
	SET @Date = CASE WHEN DAY(@Date) < 15 THEN @Date + 15 ELSE DATEADD(mm,1,@Date)-15 END
RETURN @Date
END


